package com.zhongxi.guoyuan.view.seller;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.CoinRecorderAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.coinStoreOrder.CoinRecorderData;
import com.zhongxi.guoyuan.entity.coinStoreOrder.CoinRecorderResult;
import com.zhongxi.guoyuan.entity.seller.CoinCenterResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import android.support.annotation.RequiresApi;

public class SellerCoinStoreOrderActivity extends BaseActivity implements View.OnClickListener, PullToRefreshBase.OnRefreshListener2<ListView> {

    private PullToRefreshListView lvList;
    private List<CoinRecorderData> data = new ArrayList<CoinRecorderData>();
    private TextView tvStartTime;
    private TextView tvEndTime;
    private DatePickerDialog dialog;
    private RelativeLayout relaComplain;
    private TextView tvName;
    private TextView tvCoinId;
    private TextView tvCoinPhone;
    private TextView tvAllCoin;
    private TextView tvComplain;
    private TextView tvCoinQuery;
    private String type;
    private Map<String, String> map = new HashMap<>();
    private String startTime;
    private String endTime;
    private EditText etPhone;
    private CoinRecorderAdapter adapter;
    private TextView tvQuery;
    private String complainNum;
    private TextView tvApply;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_seller_coin_store_order);
        initTitle();
        tvTitle.setText("银币商家中心");
        lvList = (PullToRefreshListView) findViewById(R.id.lvList);
        tvStartTime = (TextView) findViewById(R.id.tvStartTime);
        tvEndTime = (TextView) findViewById(R.id.tvEndTime);
        relaComplain = (RelativeLayout) findViewById(R.id.relaComplain);
        etPhone = (EditText) findViewById(R.id.etPhone);


        tvName = (TextView) findViewById(R.id.tvName);
        tvCoinId = (TextView) findViewById(R.id.tvCoinId);
        tvCoinPhone = (TextView) findViewById(R.id.tvCoinPhone);
        tvAllCoin = (TextView) findViewById(R.id.tvAllCoin);
        tvComplain = (TextView) findViewById(R.id.tvComplain);
        tvCoinQuery = (TextView) findViewById(R.id.tvCoinQuery);
        tvQuery = (TextView) findViewById(R.id.tvQuery);
        tvApply = (TextView) findViewById(R.id.tvApply);
    }

    @Override
    protected void initData() {
        super.initData();
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateNowStr = sdf.format(now);
        tvStartTime.setText(dateNowStr);
        tvEndTime.setText(dateNowStr);
        startTime = endTime = dateNowStr;
        adapter = new CoinRecorderAdapter(context, data);
        lvList.setAdapter(adapter);
        type = "info";
        getServer(Url.SILVER, null, "", true, null, "get");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try{
            if("info".equals(type)){
                CoinCenterResult result = gson.fromJson(response, CoinCenterResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                getRecorder();
                initCoinData(result);
            }else if("recorder".equals(type)){
                CoinRecorderResult result = gson.fromJson(response, CoinRecorderResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if(pageNum==1){
                    data.clear();
                }
                if(result.getData().size()>0){
                    data.addAll(result.getData());
                }
                lvList.onRefreshComplete();
                adapter.notifyDataSetChanged();
                if(null!=result.getSilverNum()&&!"".equals(result.getSilverNum())){
                    tvCoinQuery.setText(result.getSilverNum()+"银币");
                }else{
                    tvCoinQuery.setText("*银币");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse result = gson.fromJson(response, BaseResponse.class);
        if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj())){
            MyApplication.getInstance().setSpValue(result.getSafeobj());
        }
        if(9002==result.getCode()){
            showShortToast("登陆已失效，请重新登陆");
            SharedPreferences sharedPrefrences = getSharedPreferences(Url.APP_SP, MODE_PRIVATE);
            sharedPrefrences.edit().putString("coincredentials", "").commit();
            startAct(SellerCoinStoreLoginActivity.class);
        }else if(result.getCode() ==9003){
            showShortToast("您的店铺已关闭，请联系美容院");
        }
    }

    /**
     * 线下消费商家检索详情
     */
    private void getRecorder() {
        if(CommonTool.TimeCompare(startTime, endTime)){
            String phone = etPhone.getText().toString().trim();
            type = "recorder";
            map.put("stime", startTime);
            map.put("etime", endTime);
            if(null!=phone&&!"".equals(phone)){
                map.put("userphone", phone);
            }else{
                map.put("userphone", "");
            }
            String str = "&page="+pageNum;
            getServer(Url.SILVER_DETAILS, map, str, true, null, "post");
        }else {
            showShortToast("结束时间不能小于开始时间");
        }
    }

    /**
     * 初始化数据
     * @param result
     */
    private void initCoinData(CoinCenterResult result) {
        if(null!=result.getData().getName()&&!"".equals(result.getData().getName())){
            tvName.setText(result.getData().getName());
        }else{
            tvName.setText("");
        }
        if(null!=result.getData().getId()&&!"".equals(result.getData().getId())){
            tvCoinId.setText("商家ID:"+result.getData().getId());
        }else{
            tvCoinId.setText("商家ID:****");
        }
        if(null!=result.getData().getPhone()&&!"".equals(result.getData().getPhone())){
            tvCoinPhone.setText("商家电话："+result.getData().getPhone());
        }else{
            tvCoinPhone.setText("商家电话：");
        }
        if(null!=result.getEarningsNum()&&!"".equals(result.getEarningsNum())){
            tvAllCoin.setText(result.getEarningsNum()+"银币");
        }else{
            tvAllCoin.setText("*银币");
        }
        if(null!=result.getComplaintsNum()&&!"".equals(result.getComplaintsNum())){
            tvComplain.setText(result.getComplaintsNum()+"起");
            complainNum = result.getComplaintsNum();
        }else{
            tvComplain.setText("*起");
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        tvStartTime.setOnClickListener(this);
        tvEndTime.setOnClickListener(this);
        relaComplain.setOnClickListener(this);
        lvList.setOnRefreshListener(this);
        tvQuery.setOnClickListener(this);
        tvApply.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvStartTime:
                showDateDialog(0);
                break;
            case R.id.tvEndTime:
                showDateDialog(1);
                break;
            case R.id.relaComplain:
                Intent intent = new Intent(context, SellerCoinOrderComplainActivity.class);
                if(null!=complainNum&&!"".equals(complainNum)){
                    intent.putExtra("complainNum", complainNum);
                }else{
                    intent.putExtra("complainNum", "*");
                }
                startActivity(intent);
                break;
            case R.id.tvQuery:
                getRecorder();
                break;
            case R.id.tvApply:
                startAct(SellerCoinExchangeActivity.class);
                break;
        }
    }

    private void showDateDialog(final int index) {
        Calendar c = Calendar.getInstance();
        dialog = new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                String mon = month+1+"";
                String text = year + "-" + mon + "-" + dayOfMonth;
                if(index == 0){
                    tvStartTime.setText(text);
                    startTime = text;
                }else if(index == 1){
                    tvEndTime.setText(text);
                    endTime = text;
                }
                getRecorder();
            }
        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
        dialog.setTitle("请选择时间：");
        dialog.getDatePicker().setCalendarViewShown(false);
        dialog.show();
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum = 1;
        getRecorder();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum++;
        getRecorder();
    }
}
